<?php
/**
 * Created by PhpStorm.
 * User: junyv
 * Date: 2016/9/18
 * Time: 11:52
 * 微信消息群发
 */

namespace app\manage\controller;
set_time_limit(0);
class WeixinMsgGroup extends Base
{
//前置操作定义
    protected $beforeActionList = [
        'beforeEdit'  =>  ['only'=>'add'],
    ];
    private $mod;
    private $_cate_mod;
    public function _initialize(){
        parent::_initialize();
        $this->mod = model('weixin_msg_group');
        $this->_cate_mod = model('article_cate');
        $this->list_field = 'id,title,create_time,author,ordid,update_time,is_send';
        $this->sort = 'ordid asc,id';
    }
    public function _search(){
        $map = '';
        ($title = input('get.keyword')) && $map['title'] = ['like','%'.$title.'%'];
        $status = input('get.status',0);//默认显示未发送的消息
        $status>=0 && $map['is_send'] = ['eq',$status];
        $this->assign('search', array(
            'is_send'  => $status,
            'keyword' => $title
        ));
        return $map;
    }
    public function beforeEdit(){
        $id = input('param.id/d');
        $article = model('article')->withTrashed()->field('id,cate_id')->where(['id'=>$id])->find();
        $spid = $this->_cate_mod->where(['id'=>$article['cate_id']])->value('spid');
        if( $spid==0 ){
            $spid = $article['cate_id'];
        }else{
            $spid .= $article['cate_id'];
        }

        $this->assign('selected_ids',$spid);
    }
    public function addDo(){
        $this->_name = 'article';
        \app\common\model\Article::event('before_insert',function($obj){
            if(empty($obj->img)){
                $this->errMsg = '请选择缩略图';
                return false;
            }
            $obj->cate_alias = $this->_cate_mod->getCateAlias($obj->cate_id);
            return true;
        });
        \app\common\model\Article::event('after_insert',function($obj){
            //添加到消息群发表中
                $info     = $this->getContent($obj->info,$obj->img);
                $add_data['aid']                = $obj->id;
                $add_data['content_source_url'] = $this->getUrl($obj->id,'article');//url('Article/detail@'.$siteInfo['domain'],['id'=>$obj->id]);
                $add_data['author']             = cache('site')['title'];
                $add_data['digest']             = msubstr($obj->description,0,54);
                $add_data['content']            = $info['content'];
                $add_data['thumb_media_id']     = $info['thumb'];
                $add_data['title']              = $obj->title;
            model('weixin_msg_group')->save($add_data);
            return true;
        });
        parent::addDo();
    }

    public function delete(){
        parent::delete();
    }
    public function sendMsg(){
        $pk = $this->mod->getPk();
        $ids = trim(input($pk), ',');
        $field = 'title,author,content,content_source_url,thumb_media_id,digest';
        $map['id']   = ['in',$ids];
        $lists = $this->mod->where($map)->field($field)->order('ordid asc,id desc')->select();
        $errno = 0;
        $errmsg = '';
        if($lists){
            $data['articles'] = objToArray($lists);
            $media = controller('manage/Weixin','event');
            $media->init();
            $return = $media->uploadArticles($data);//上传到微信服务器
            if($return['errcode'] == 0){
                $this->mod->save(['media_id'=>$return['media_id']],$map);
                //上传成功执行群发
                $msg = [
                    'filter' => [
                        'is_to_all' => true,
                    ],
                    //"towxname"=>'junyvv',
                    'mpnews' => [
                        'media_id' => $return['media_id']
                    ],
                    'msgtype' => 'mpnews'
                ];
                $media->init('Receive');
                //$result = $media->previewMassMessage($msg);
                $result = $media->sendMsg($msg);//发送消息
                if($result['errcode'] == 0){
                    $this->mod->where($map)->update(['is_send'=>1]);
                    $errno = 1;
                    $errmsg = '消息发送成功';
                }else{
                    $errmsg = '消息发送失败：'.$result['errmsg'];
                }
            }else{
                $errmsg = '消息上传失败：'.$return['errmsg'];
            }
        }else{
            $errmsg = '暂无可用图文';
        }
        $this->ajaxReturn($errno,$errmsg);
    }

    /**
     * @param $info
     * 正则取出内容中的所有图片
     */
    private function getContent($content,$img=''){
        $media = controller('manage/Weixin','event');
        $media->init();
        if(preg_match_all("/(src)=([\"|'][^http|https\:\/\/]?)([^ \"'>]+\.(gif|jpg|jpeg|bmp|png))\\2/i", $content, $matches)) {
            $return = $media->uploadImgToWeixin($matches[3]);
            $content = strtr($content,$return);
        }
        $thumb = '1';
        if($img){
            $thumb = $media->uploadThumb($img);
        }
        return ['content'=>$content,'thumb'=>$thumb];
    }
    private function getUrl($id,$model){
        $config = [
            'article' => '/news/',
        ];
        $url = 'http://'.config('domain.mobile').$config[$model].$id.'.html';
        return $url;
    }
}